import {Component, OnDestroy, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {ValidationService} from "@shared/service/validator/validator.service";

import {PlaceParam} from "@shared/components/regio-picker/regio-picker.component";
import {ModalComponent} from "@shared/components/modal/modal.component";
import {ToolsService} from "@shared/service/tools/tools.service";
import {SaleService} from "@sale/sale.service";
import {Subject} from "rxjs/Rx";
import {ActivatedRoute, Router} from "@angular/router";
// import {TrainSchoolSimpleVO} from "@interface/sale.model";
import {AuthService} from "@shared/service/auth/auth.service";

import {certificate} from "@sign-up/personal/train/train.model";
import {PresentData, TrainSchoolSimpleVO} from "@interface/index";
// import {PresentData} from "@interface/shared.model";



@Component({
  selector: 'seed-add-customer',
  templateUrl: './add-customer.component.html',
  styleUrls: ['./add-customer.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class SaleAddCustomerComponent implements OnInit, OnDestroy {
  public orgUserId: string;
  public signForm: FormGroup;
  public certificateArr = certificate;
  public origineArr = [
    {title: '地推', value: 1},
    {title: '传单', value: 2},
    {title: '转介绍', value: 3},
    {title: '地摊', value: 4},
    {title: '公开课', value: 5},
    {title: '电销', value: 6},
    {title: '微信', value: 7}
  ];
  public schoolList: TrainSchoolSimpleVO[] = [];
  public origin: {
    text: string;
    choose: PlaceParam;
    hasChange: boolean;
  } = {
    text: '请选择籍贯',
    choose: new PlaceParam(),
    hasChange: false
  };
  @ViewChild(ModalComponent) modal;
  public ngUnsubscribe: Subject<void> = new Subject<void>();

  constructor(
    private formBuilder: FormBuilder,
    private tools: ToolsService,
    private saleService: SaleService,
    private router: Router,
    private route: ActivatedRoute,
    private authService: AuthService
  ) {
    this.route.params.subscribe(param => {
      this.orgUserId = this.authService.getAuthOrgId();
      this.getOrgInfo();
    });
    this.formInit();
  }

  formInit() {
    // 证件号
    this.signForm = this.formBuilder.group({
      'name': ['', [Validators.required, ValidationService.nickNameSpaceValidator, Validators.minLength(1), Validators.maxLength(40)]],
      'parentMobile': ['', [Validators.required, ValidationService.accountValidator]],
      'email': ['', [Validators.maxLength(100)]],
      'sex': ['', [Validators.required]],
      'address': ['', [Validators.required, Validators.maxLength(200)]],
      'weight': ['', [Validators.max(300)]],
      'height': ['', [Validators.max(200)]],
      'origine': ['', [Validators.required]],
      'advisorySchoolId': ['', [Validators.required]]
    });
    const numValidator = [Validators.maxLength(20)];
    const IdControl = this.formBuilder.group({
      'num': new FormControl('', numValidator),
      'certificate': new FormControl('', []),
    });
    this.signForm.addControl('idNo', IdControl);
    // 身份证
    const varlidator = ValidationService.matChingIDNum('idNo');
    this.signForm.setValidators(varlidator);
    // this.signForm.valueChanges.subscribe(res => {
    //   console.log(this.signForm)
    // });
  }

  // 获取机构信息
  getOrgInfo() {
    this.saleService.getOrgCampus(this.orgUserId)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        if (res.result === '0') {
          this.schoolList = res.data;
        } else {
          this.tools.showToast(res.msg);
        }
      });
  }

  // 选择证件类型
  certificateChange(val) {
    this.signForm.controls['idNo'].patchValue({'certificate': val});
  }

  // 选择客户来源
  selectOrigin(val) {
    this.signForm.controls['origine'].setValue(val);
  }

  // 选择校区
  selectSchool(val) {
    this.signForm.controls['advisorySchoolId'].setValue(val);
  }

  showArea() {
    this.modal.show();
  }

  /**
   * 选择籍贯完成
   * @param {PlaceParam} val
   */
  pickerFinish(val: PlaceParam) {
    // console.log(val);
    this.origin.choose = val;
    // 判断有没有城市名，如果没有则是直辖市，只去省级和区域
    const txt = val.cityName ? val.provinceName + ' ' + val.cityName : val.provinceName + ' ' + val.districtName;
    this.origin.text = txt;
    this.origin.hasChange = true;
    this.modal.hide();
    this.modal.goBack();
  }

  sign() {
    const formData = this.signForm.value;
    const data = {};
    data['orgUserId'] = this.orgUserId;
    Object.keys(formData).forEach(key => {
      // console.log(formData[key]);
      if (!!formData[key]) {
        this.setReqData(key, formData, data);
      }
    });
    if (this.origin.hasChange) {
      const province = this.origin.choose.provinceId;
      const city = this.origin.choose.cityId ? this.origin.choose.cityId : this.origin.choose.districtId;
      data['origin'] = province + ',' + city;
    }
    // console.log(data);
    this.tools.showLoading();
    this.saleService.addCustomer(data)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        this.tools.hideLoading();
        if (res.result === '0') {
          this.tools.showToast('添加客户成功');
          setTimeout(() => {
            // this.router.navigate([`/sale/customer-list`]);
            history.back();
          }, 1500);
        } else if (res.result === '40107') {  //  已存在信息，在请求一次是否覆盖
          const tip: PresentData = {};
          tip.title = res.msg + ' , 是否覆盖?';
          tip.message = [];
          tip.cancelBtn = true;
          tip.confirmText = '覆盖';
          if (res.data.name) {
            tip.message.push(`姓名: ${res.data.name}`);
          }
          if (res.data.phone) {
            tip.message.push(`电话: ${res.data.phone}`);
          }
          if (res.data.sex) {
            const sexArr = ['', '男', '女', '保密'];
            tip.message.push(`性别: ${sexArr[res.data.sex]}`);
          }
          this.tools.present(tip).then(presentRes => {
            if (presentRes) {
              data['isCover'] = 1;
            } else {
              data['isCover'] = 2;
            }
            this.saleService.addCustomer(data).subscribe(secRes => {
              if (secRes.result === '0') {
                this.tools.showToast('添加客户成功');
                setTimeout(() => {
                  // this.router.navigate([`/sale/customer-list`]);
                  history.back();
                }, 1500);
              } else {
                this.tools.showToast(res.msg);
              }
            });
          });
        } else {
          this.tools.showToast(res.msg);
        }
      });
  }

  /**
   * 判断变字段,设置值
   * @param {string} key
   * @param FormData
   * @param data
   */
  setReqData(key: string, FormData: any, data: any) {
    switch (key) {
      case 'idNo':
        data['idType'] = FormData[key]['certificate'];
        data['idNo'] = FormData[key]['num'];
        return;
      case 'name':
        data[key] = FormData[key].replace(/(^\s*)|(\s*$)/g, '');
        return;
      default:
        data[key] = FormData[key];
        return;
    }
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}
